package com.xhtt.modules.app.controller.cfg;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.exception.RRExceptionEnum;
import com.xhtt.common.utils.*;
import com.xhtt.modules.app.annotation.Login;
import com.xhtt.modules.app.annotation.LoginUser;
import com.xhtt.modules.cfg.entity.CfgHoseInfo;
import com.xhtt.modules.cfg.entity.CfgHoseProduct;
import com.xhtt.modules.cfg.model.ValidHoseParam;
import com.xhtt.modules.cfg.service.CfgHoseInfoService;
import com.xhtt.modules.cfg.service.CfgHoseProductService;
import com.xhtt.modules.sys.controller.AbstractController;
import com.xhtt.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 软管库 前端控制器
 * </p>
 *
 * @author feipc
 * @since 2019-02-20
 */
@Api(tags = "任务平台-基础数据维护-软管库列表", value = "任务平台-基础数据维护-软管库列表")
@RestController
@RequestMapping("app/sys/cfg/hose")
public class CfgHoseInfoController extends AbstractController {

    @Autowired
    private CfgHoseInfoService cfgHoseInfoService;
    @Autowired
    private CfgHoseProductService cfgHoseProductService;

    /**
     * 获取软管库列表
     */
    @GetMapping(value = "/list")
    @ApiOperation("获取软管库列表(web/app)")
    @Login
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = cfgHoseInfoService.queryPage(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 获取可用软管列表
     */
    @GetMapping(value = "/validList")
    @ApiOperation("获取可用软管列表(web)")
    @Login
    public R validList(ValidHoseParam param) {
        Integer productId = param.getProductId();
        List<Integer> selectedIds = param.getSelectedIds();
        String pressureLevel;
        String first = param.getPositionFirst();
        String second = param.getPositionSecond();
        if ("码头区".equals(first) || "码头区".equals(second)) {
            pressureLevel = "1";
        } else {
            pressureLevel = "2";
        }

        List<CfgHoseInfo> list = cfgHoseInfoService.validList(productId, pressureLevel);
        if (CollectionUtils.isNotEmpty(selectedIds)) {
            List<CfgHoseInfo> nlist = list.stream().filter(cfgHoseInfo -> !selectedIds.contains(cfgHoseInfo.getId())).collect(Collectors.toList());
            return R.ok().put(Constant.DATA, nlist);
        }

        return R.ok().put(Constant.DATA, list);
    }

    /**
     * 新增软管库
     */
    @PostMapping(value = "/addHose")
    @ApiOperation("新增软管库(web)")
    @Login
    public R addHose(@RequestBody CfgHoseInfo cfgHoseInfo) {
        cfgHoseInfoService.addHose(cfgHoseInfo);
        return R.ok();
    }

    /**
     * 删除软管库
     */
    @PostMapping(value = "/delete")
    @ApiOperation("删除软管库(web)")
    @Login
    public R delete(@RequestBody Integer[] ids) {
        //假删除
        CfgHoseInfo h = new CfgHoseInfo();
        h.setStatus(-1);
        cfgHoseInfoService.update(h, new UpdateWrapper<CfgHoseInfo>().in(CfgHoseInfo.ID, Arrays.asList(ids)));
        return R.ok();
    }

    /**
     * 修改软管库
     */
    @PostMapping(value = "/updateHose")
    @ApiOperation("修改软管库(web)")
    @Login
    public R updateHose(@RequestBody CfgHoseInfo cfgHoseInfo, @ApiIgnore @LoginUser SysUserEntity user) {
        MDC.put("deptUser", user.getDeptName() + "-" + user.getName());
        cfgHoseInfoService.updateHose(cfgHoseInfo);
        return R.ok();
    }

    /**
     * app修改rfid
     */
    @PostMapping(value = "/updateRfid")
    @ApiOperation("app修改rfid(app)")
    @Login
    public R updateRfid(@RequestBody CfgHoseInfo cfgHoseInfo, @ApiIgnore @LoginUser SysUserEntity user) {
        MDC.put("deptUser", user.getDeptName() + "-" + user.getName());
        cfgHoseInfoService.updateHoseRfid(cfgHoseInfo);
        return R.ok();
    }

    /**
     * 获取软管修改日志
     */
    @GetMapping(value = "/logList")
    @ApiOperation("获取软管修改日志(web)")
    @Login
    public R logList(@RequestParam Map<String, Object> params) {
        PageUtils page = cfgHoseInfoService.logList(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 获取软管
     */
    @GetMapping(value = "/get/{id}")
    @ApiOperation("获取软管(web/app)")
    @Login
    public R get(@PathVariable("id") Integer id) {
        CfgHoseInfo hoseInfo = cfgHoseInfoService.getById(id);
        List<CfgHoseProduct> hoseProducts = cfgHoseProductService.list(new LambdaQueryWrapper<CfgHoseProduct>().eq(CfgHoseProduct::getHoseId, hoseInfo.getId()));
        hoseInfo.setComProduct(hoseProducts.stream().filter(cfgHoseProduct -> cfgHoseProduct.getType().intValue() == 1).collect(Collectors.toList()).get(0));
        hoseInfo.setSpareProducts(hoseProducts.stream().filter(cfgHoseProduct -> cfgHoseProduct.getType().intValue() == 2).collect(Collectors.toList()));
        return R.ok().put(Constant.DATA, hoseInfo);
    }

    @PostMapping(value = "/upload")
    @ApiOperation("软管导入")
    @Login
    public R upload(MultipartFile file) {
        Map<Long, Map<Integer, String>> map = ReadExcel.readExcel(file, 1);
        cfgHoseInfoService.upload(map);
        return R.ok();
    }

    @GetMapping(value = "/mouldExport")
    @ApiOperation("软管模板下载")
    public void mouldExport(HttpServletResponse response) {
        String fileName = "软管信息导入模板.xls";
        String path = "templates/outHose.xls";
        DownloadFile.exportFile(fileName, path, response);
    }

    @GetMapping(value = "/export")
    @ApiOperation("软管导出")
    @Login
    public void export(HttpServletResponse response, @RequestParam Map<String, Object> params) {
        cfgHoseInfoService.exportExcel(response, params);
    }

    @GetMapping(value = "/logExport")
    @ApiOperation("软管操作记录导出")
    @Login
    public void logExport(HttpServletResponse response, @RequestParam Map<String, Object> params) {
        ExportExcel exportExcel = new ExportExcel();
        Object hoseId = params.get("id");
        CfgHoseInfo hose = cfgHoseInfoService.getOne(new LambdaQueryWrapper<CfgHoseInfo>().eq(CfgHoseInfo::getId,hoseId).select(CfgHoseInfo::getId,CfgHoseInfo::getNumberNo));
        PageUtils page = cfgHoseInfoService.logList(params);
        List list = page.getList();
        String fileName = "软管("+hose.getNumberNo()+")操作记录";
        String sheetName = "软管操作记录";
        String[] headers = {"记录时间", "操作人", "压力等级", "目前产品", "备用产品", "RFID", "报废时间", "上次打压时间"};
        String[] columns = {"createTime", "deptUser", "pressureLevelInfo", "comProductInfo", "spareProductInfo", "rfidInfo", "dateScrapInfo", "dateSuppressInfo"};
        try {
            exportExcel.exportExcel(fileName, sheetName, headers, columns, list, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException(RRExceptionEnum.EXPORT_FAIL);
        }
    }

}
